
/**
 * @ProjectName: 
 * @Copyright: 2014 lisheng  All Right Reserved.
 * @address: toughheart@163.com
 * @date: 2015年4月6日 上午10:54:42
 * @Description: 本内容未经本人允许禁止使用、转发.
 */
 
package com.ls.fw.web.core.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 
 * @author lisheng
 * @date 2015年4月6日 上午10:54:42
 * @version V1.0 
 */
public class ResourceLoadUtil {
	protected static final Logger logger = LoggerFactory.getLogger(ResourceLoadUtil.class);
	 
	public static InputStream getResourceStream(String resourceName, ServletContext context, boolean failIfNotFound) throws IOException {
		InputStream is = null;

		logger.debug("正试图到classpath加载"+resourceName);
		/** try classpath **/
		is = ResourceLoadUtil.class.getClassLoader().getResourceAsStream(resourceName);

		/** try web context **/
		if (is == null) {
			logger.debug("正试图到web context加载"+resourceName);
			String fileName = context.getRealPath(resourceName);
            if (fileName != null) {
                File file = new File(fileName);

                if (file.exists()) {
                    is = new FileInputStream(fileName);
                }
            }
		}

		/** try current directory **/
		if (is == null) {
			File file = new File(resourceName);
			logger.debug("正试图到"+resourceName+"加载"+resourceName);
			if (file.exists()) {
				is = new FileInputStream(resourceName);
			}
		}

		/** fail if still empty **/
		if (is == null && failIfNotFound) {
			throw new IOException(String.format("unable to locate resource - %s", resourceName));
		}

		return is;
	}
}
